<template>
  <div class="con">
    <el-form
      :model="formData"
      label-width="70px"
      :inline="true"
      ref="formEle"
      class="flex formTop"
    >
      <el-form-item label="用户ID" prop="userId">
        <el-input v-model="formData.userId" placeholder="请输入用户ID查找" />
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="formData.userName" placeholder="请输入用户名查找" />
      </el-form-item>
      <el-form-item label="用户状态" prop="state">
        <el-select v-model="formData.state">
          <el-option label="所有" :value="0" />
          <el-option label="在职" :value="1" />
          <el-option label="离职" :value="2" />
          <el-option label="试用期" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formEle)">查询</el-button>
        <el-button @click="resetForm(formEle)">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <div class="table-list">
      <div class="btnTop">
        <el-button type="primary" @click="AddList">新增</el-button>
        <el-button type="danger" @click="batchesDel">批量删除</el-button>
      </div>
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-for="(item, index) in columns"
          :key="index"
          :prop="item.property"
          :label="item.label"
          :formatter="item.formatter"
        ></el-table-column>
        <el-table-column label="操作" class="last-btn">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageData.pageSize"
        v-model:page-size="pageData.pageNum"
        :page-sizes="[1, 3, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <el-dialog
    v-model="dialogFormVisible"
    :title="dialogFormType == 'Edit' ? '编辑' : '新增用户'"
    @closed="clearDialog"
  >
    <el-form
      :model="dialogFormData"
      :label-width="formLabelWidth"
      ref="dialogForm"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="dialogFormData.userName" />
      </el-form-item>
      <el-form-item label="邮箱" prop="userEmail">
        <el-input v-model="dialogFormData.userEmail">
          <template #append>@qq.com</template>
        </el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="dialogFormData.mobile" />
      </el-form-item>
      <el-form-item label="岗位" prop="job">
        <el-input v-model="dialogFormData.job" />
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="dialogFormData.state" placeholder="请选择">
          <el-option label="在职" :value="1" />
          <el-option label="离职" :value="2" />
          <el-option label="试用期" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="系统角色" prop="roleName">
        <el-select
          v-model="dialogFormData.roleList"
          placeholder="请选择"
          multiple
        >
          <el-option
            :label="item.roleName"
            v-for="(item, index) in RoleList"
            :value="item._id"
            :key="item._id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <el-cascader
          v-model="dialogFormData.deptId"
          :options="DeptList"
          :props="{ checkStrictly: true, value: '_id', label: 'deptName' }"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogConfirm(dialogForm)">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, toRefs } from "vue";
import type { FormInstance } from "element-plus";
import request from "../api/requestApi";
import { AxiosResponse } from "axios";
import { formateDate, showMassage } from "../untils/common";
import { userinfo, User, reqResult } from "@/types/type";
import { log } from "console";
// 表单数据
let formData = reactive({
  userId: "",
  userName: "",
  state: 1,
});

let pageData = reactive({
  pageSize: 1, // 页数
  pageNum: 10, // 一页的数量
  total: 0, // 全部
});

const formEle = ref<FormInstance>();
// 提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      reqUserList();
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 总数
let { total } = toRefs(pageData);
// 重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
// table字段
let columns = [
  {
    property: "userId",
    label: "用户Id",
  },
  {
    property: "userName",
    label: "用户名称",
  },
  {
    property: "userEmail",
    label: "用户邮箱",
  },
  {
    property: "role",
    label: "用户角色",
    formatter(roe: string, column: string, cellValue: string) {
      return {
        0: "管理员",
        1: "普通用户",
      }[cellValue];
    },
  },
  {
    property: "state",
    label: "用户状态",
    formatter(roe: string, column: string, cellValue: string) {
      return {
        1: "在职",
        2: "离职",
        3: "试用期",
      }[cellValue];
    },
  },
  {
    property: "createTime",
    label: "注册时间",
    formatter(roe: string, column: string, cellValue: string) {
      return formateDate(new Date(cellValue));
    },
  },
  {
    property: "lastLoginTime",
    label: "最后登录时间",
    formatter(roe: string, column: string, cellValue: string) {
      return formateDate(new Date(cellValue));
    },
  },
];
const multipleSelection = ref<string[]>([]);
let selections = ref<userinfo[]>([]);
// 当选择项发生改变时触发
async function handleSelectionChange(selection: userinfo[]) {
  console.log(selection);
  selections.value = selection;
}

// 编辑与删除
const handleEdit = (index: number, row: userinfo) => {
  openDialog("Edit");
  Object.assign(dialogFormData, row);
};
const handleDelete = async (index: number, row: userinfo) => {
  let res = await request.delUser({ userIds: row.userId });
  reqUserList();
};

// 新增与批量删除
const AddList = () => {
  openDialog("Add");
};
const batchesDel = async () => {
  selections.value.forEach((item) => {
    multipleSelection.value.push(item.userId);
  });
  let res = await request.delUser({ userIds: multipleSelection.value });
  reqUserList();
};

// 改变当前页
const handleCurrentChange = (value: number) => {
  pageData.pageSize = value;
  reqUserList();
};
// 改变一页的个数
const handleSizeChange = (value: number) => {
  pageData.pageNum = value;
  reqUserList();
};




onMounted(() => {
  Promise.all([reqUserList(), reqRoleList(), reqDeptList()]);
});
// 获取用户列表
const tableData = ref<object[]>([]);
const RoleList = ref<object[]>([]);
const DeptList = ref<object[]>([]);
// 系统用户列表请求
async function reqUserList() {
  const res = (await request.getUserList({
    ...formData,
    ...pageData,
  })) as AxiosResponse;
  tableData.value = res.data.page.list;
  console.log(tableData.value);
  total.value = res.data.page.total;
}
// 系统角色请求
async function reqRoleList() {
  const res = (await request.getRoleList({})) as AxiosResponse;
  RoleList.value = res.data.list;
}
// 系统部门请求
async function reqDeptList() {
  const res = (await request.getDeptList()) as AxiosResponse;
  DeptList.value = res.data;
}




// dialog模态框
const dialogFormVisible = ref(false); // 开关
const dialogFormType = ref<string>("");
// 表单实例对象
let dialogForm = ref<FormInstance>();
let formLabelWidth = ref<string>("100px");
// 打开模态框
function openDialog(type: string) {
  dialogFormVisible.value = true;
  dialogFormType.value = type;
}
const dialogFormData = reactive<User>({
  // ?类型
  userId: "",
  userName: "",
  userEmail: "",
  mobile: "",
  job: "",
  state: "",
  roleList: [],
  roleName: "",
  deptId: [],
});
// 关闭对话框
function clearDialog() {
  for (let key in dialogFormData) {
    dialogFormData[key] = "";
  }
}
// 对话框确认
function dialogConfirm(formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      // dialogFormData.userEmail += "@qq.com";
      dialogFormData.type = dialogFormType.value;
      let res = (await request.EditUser(dialogFormData)) as reqResult<null>;
      console.log(res,"111");
      // 参数错误
      if (res.code == 200) {
        reqUserList();
        showMassage(res.msg, "success");
      } else {
        showMassage(res.msg, "error");
      }
    } else {
      console.log(fields);
    }
  });
  dialogFormVisible.value = false;
}
</script>

<style lang="postcss" scoped>
.con{
  @apply flex-1 flex flex-col;
  width: 100%;
}
.formTop {
  height: 60px;
  @apply bg-light-50;
  line-height: 60px;
  border-radius: 5px;
  justify-content: space-between;
  .el-form-item {
    margin-bottom: 0;
    align-self: center;
  }
}
.table-list {
  @apply bg-light-50 flex-1 flex flex-col;
  border-radius: 5px;
  overflow: hidden;
  margin: 20px 0 0 0;
  .btnTop {
    padding: 20px;
  }
  .el-pagination {
    margin: auto auto 0;
    height: 50px;
  }
}
.el-form :deep(.el-form-item__content) {
  flex-wrap: nowrap;
}
.el-table :deep(.el-table__cell) {
  padding: 15px 0;
}
</style>
